import datetime

from marshmallow import fields
from werkzeug.security import generate_password_hash, check_password_hash

from apps.extensions import db, ma
from flask_login import UserMixin


class User(db.Model, UserMixin):
    __tablename__ = 'admin_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
    username = db.Column(db.String(20), comment='用户名')
    password = db.Column(db.String(128), comment='哈希密码')
    salt = db.Column(db.String(128), comment='哈希密码')
    deleted = db.Column(db.Integer, default=0, comment='启用')
    create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='创建时间')

    def gen_password(self, password):
        return generate_password_hash(password+"#"+self.salt)

    def validate_password(self, password):
        return check_password_hash(self.password, password+"#"+self.salt)


class UserPageOut(ma.Schema):
    id = fields.Integer()
    roleName = fields.Str(attribute="name")
    roleCode = fields.Str(attribute="code")
    enable = fields.Str()
    remark = fields.Str()
    details = fields.Str()
    sort = fields.Integer()
    create_at = fields.DateTime()
    update_at = fields.DateTime()